<template>
    <div v-if="show"  style="border: 1px solid #ccc;">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
        <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
            @onCreated="handleCreated"
            @onChange="handleChange"
            />
           
    </div>
</template>
<script setup>

import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, onDeactivated, watch, onActivated } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import { uploadFile } from '@/api/supportApi';
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref('simple')
// 内容 HTML
const valueHtml = ref()
const value = defineModel('value')
const show = ref(true)


const toolbarConfig = {
    toolbarKeys : ['blockquote', 'bold', 'underline', 'italic', 'through', 'color', 'bgColor', 'fontSize', 'justifyLeft', 'justifyRight', 'justifyCenter',  'lineHeight', "uploadImage", "uploadVideo", 'insertVideo', 'clearStyle', ]
}
const editorConfig = {
    placeholder: '请输入内容...',
    'MENU_CONF': {
        uploadImage: {
            async customUpload(file, insertFn) {

                const formData = new FormData();
                formData.append('file', file);

                let res = await uploadFile(formData, () => { })
                // 自己实现上传，并得到图片 url alt href
                // 最后插入图片
                insertFn(res, '', '')
            },
        },
        uploadVideo: {
            // 自定义上传
            async customUpload(file, insertFn) {
                const formData = new FormData();
                formData.append('file', file);

                let res = await uploadFile(formData, () => { })
                insertFn(res, '')
            }
        }
    }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

onActivated(() => {
    
    show.value = true
})
onDeactivated(() => {
    show.value = false
})


const handleCreated = (editor) => {
    
    valueHtml.value = value.value
    editorRef.value = editor // 记录 editor 实例，重要！
    console.log(editor)
    console.log(editor.getAllMenuKeys())
    console.log(editor.getMenuConfig('uploadVideo'))
  

}
const handleChange = (editor) => {
    value.value = valueHtml.value
    
}
</script>
<style scoped></style>